<template>
  <Swiper
    class="custom-swiper"
    @swiper="onSwiper"
    :autoplay="{ delay: 1000, pauseOnMouseEnter: true }"
    loop
    :modules="modules"
    :pagination="{
      el: customPageBarRef,
      type: 'custom',
      renderCustom: renderCustom,
      clickable: true,
    }"
  >
    <SwiperSlide v-for="(item, idx) in imgList" :key="item">
      <div class="relative">
        <img :src="item" alt="" />
        <div class="absolute bottom-4 left-6 z-10 text-white text-xl font-bold">第{{ idx + 1 }}张</div>
      </div>
    </SwiperSlide>
  </Swiper>
  <div class="flex flex-row justify-center items-center gap-2 text-white" ref="customPageBarRef">
    <template v-for="(item, index) in totalSlides" :key="item">
      <span
        v-if="currentIndex == index"
        class="px-10 active-page-item cursor-pointer"
        @mouseover="() => onToSlide(index)"
        @mouseout="onStartPlay"
        >{{ item }}</span
      >
      <span v-else class="px-2 bg-red-300 cursor-pointer" @mouseover="() => onToSlide(index)" @mouseout="onStartPlay">{{
        item
      }}</span>
    </template>
  </div>
</template>

<script setup lang="ts">
import { Autoplay, Pagination } from 'swiper'
import type { Swiper } from 'swiper'
import 'swiper/css/autoplay'
import 'swiper/css/pagination'
import { ref } from 'vue'

const modules = [Autoplay, Pagination]
//@ts-ignore
const basePath = import.meta.env.BASE_URL
console.log('basePath', basePath)
const imgList = new Array(4).fill(true).map((_, index) => `${basePath}swiper-pic/0${index + 1}.jpg`)

const customPageBarRef = ref<HTMLDivElement>()
const currentIndex = ref<number>(0)
const totalSlides = ref<number>(0)
function renderCustom(swiper: Swiper, current: number, total: number) {
  currentIndex.value = current - 1
  totalSlides.value = total
}
const swiperInstance = ref<Swiper>()
function onSwiper(swiper: Swiper) {
  swiperInstance.value = swiper
}
function onToSlide(index: number) {
  swiperInstance.value?.slideToLoop(index)
}
function onStartPlay() {
  swiperInstance.value?.autoplay.start()
}
</script>

<style scoped lang="scss">
.active-page-item {
  animation: blueToRed 1s forwards;
}
@keyframes blueToRed {
  from {
    background-color: blue;
  }
  to {
    background-color: red;
  }
}
</style>
